from PyQt5.QtMultimedia import QAudioFormat, QAudioInput, QAudioDeviceInfo, QAudio
from PyQt5.QtCore import QBuffer, QFile, QIODevice, QObject


def startRecord(dev, log,par ):
        global destinationFile, audio
        destinationFile = QBuffer()
        if(destinationFile.open( QIODevice.WriteOnly | QIODevice.Truncate )==False):
                print("Error opening file")
                return

        format = QAudioFormat()
        format.setSampleRate(8000);
        format.setChannelCount(1);
        format.setSampleSize(8);
        format.setCodec("audio/pcm");
        format.setByteOrder(QAudioFormat.LittleEndian);
        format.setSampleType(QAudioFormat.UnSignedInt);

        if(dev>=0):
                info = QAudioDeviceInfo.availableDevices(QAudio.AudioInput)[dev]
        else:
                info = QAudioDeviceInfo(QAudioDeviceInfo.defaultInputDevice())
                
        if (not(info.isFormatSupported(format))) :
                format = info.nearestFormat(format);

        audio = QAudioInput(format, par);
        audio.start(destinationFile);
        if(audio.state()!=QAudio.ActiveState):
                log("State not active")
        else:
                log("Recording with "+info.deviceName())
        print(audio.state())

def stopRecord(log):
        global destinationFile, audio
        audio.stop();
        print(destinationFile.size())
        del audio

def deviceList():
	info = QAudioDeviceInfo(QAudioDeviceInfo.defaultInputDevice())
	list = []; 
	for dev in info.availableDevices(QAudio.AudioInput):
		list.append(dev.deviceName())

	return list
	
	
